﻿#include "qmlrelayswitch.h"
#include "qdebug.h"

// Qml Function Define
mkswitchs(f_func_get)
mkswitchs(f_func_set)
mkswitchs(f_func_get_qstr)
mkswitchs(f_func_set_qstr)

QmlRelaySwitch::QmlRelaySwitch(QObject *parent)
    : QObject{parent}
{
    mkswitchs(f_var_init);
    mkswitchs(f_var_property_init);
    relayCount = e_num;
    m_settingsPath = QCoreApplication::applicationDirPath() + "/" + "settings.ini";
}

QmlRelaySwitch *QmlRelaySwitch::getInstance()
{
    static QmlRelaySwitch *myQmlRelaySwitch = new QmlRelaySwitch();
    return myQmlRelaySwitch;
}

bool QmlRelaySwitch::setSwitchStatus2MainService(int channel, bool state)
{
    log(tr("setSwitchStatus2MainService channel: %1 state : %2").arg(channel).arg(state));
    syncSwitchStatus2Qml(channel, state);
    return true;
}

void QmlRelaySwitch::syncSwitchStatus2QmlSlot(QString name, QString state)
{
    log(tr("syncSwitchStatus2QmlSlot name: %1 state: %2").arg(name, state));
    int channel = 0, status = 0;

    if (state == "off") {
        status = 0;
    } else if (state == "on") {
        status = 1;
    } else {
        log("Unknow state");
    }

    if (name == "") {
        log("Null name");
    }
    mkswitchs(f_syncSwitchStatus2Qml_1)
    else {
        log("Unknow name");
    }

    log(QString("syncSwitchStatus2QmlSlot channel: %1 status: %2").arg(channel).arg(status));
    syncSwitchStatus2Qml(channel, status);
    emit pushSwitchStatus2QmlSignal(channel, status);
}

QString QmlRelaySwitch::settingsPath() const
{
    return m_settingsPath;
}

void QmlRelaySwitch::setSettingsPath(const QString &newSettingsPath)
{
    if (m_settingsPath == newSettingsPath)
        return;
    m_settingsPath = newSettingsPath;
    emit settingsPathChanged();
}

void QmlRelaySwitch::log(QString s)
{
    QString logs = "[QmlRelaySwitch]: " + s;
    emit logsPrintSignal(logs);
    qDebug() << logs;
}

void QmlRelaySwitch::syncSwitchStatus2Qml(int channel, bool state)
{
    log(QString("syncSwitchStatus2Qml channel: %1, state: %2").arg(channel).arg(state));
    switch (channel) {
        mkswitchs(f_syncSwitchStatus2Qml);
    default:
        log(QString("syncSwitchStatus2Qml unknow channel %1").arg(channel));
        break;
    }
    if (0 < channel && channel < e_num) {
        emit pushSwitchStatus2QmlSerialPortSignal(channel, (int)state);
    }
}

void QmlRelaySwitch::resetUiSwitchStatus()
{
    mkswitchs(f_var_init);
}


